package com.qidian.k12.service.impl;

import com.qidian.k12.dto.PageInfo;
import com.qidian.k12.mapper.ScoreItemMapper;
import com.qidian.k12.mapper.StudentMapper;
import com.qidian.k12.mapper.TemplateMapper;
import com.qidian.k12.pojo.*;
import com.qidian.k12.mapper.TestScoreMapper;
import com.qidian.k12.service.TestScoreService;
import com.qidian.k12.util.K12Result;
import com.qidian.k12.vo.TestScoreSaveVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * (TestScore)表服务实现类
 *
 * @author makejava
 * @since 2021-10-30 10:25:45
 */
@Transactional
@Service("testScoreService")
public class TestScoreServiceImpl implements TestScoreService {
    @Resource
    private TestScoreMapper testScoreMapper;
    @Resource
    private ScoreItemMapper scoreItemMapper;
    @Resource
    private TemplateMapper templateMapper;
    @Resource
    private StudentMapper studentMapper;

    /**
     * 返回
     * template {templateItem}
     * student
     * testScore
     * scoreItem
     *  scoreAvgs:[{templateItemId:10,avg:61}]
     *
     *
     * @param scoreId
     * @return
     */
    @Override
    public K12Result queryDetail(long scoreId) {
        K12Result result = K12Result.ok();
        //将数据放入 map中返回
        Map map = new HashMap();
        //在成绩testScore表中查询成绩 testScore
        TestScore testScore = testScoreMapper.queryById(scoreId);
        if (testScore != null) {
            map.put("testScore", testScore);
            //在ScoreItem表中根据scoreId 查询所有scoreItem
            List<ScoreItem> scoreItems = scoreItemMapper.queryByScoreId(scoreId);
            map.put("scoreItems", scoreItems);
            // 在学生表中查询 scoreId 对应的studentNo学生信息
            Student student = studentMapper.queryById(testScore.getStudentNo());
            map.put("student", student);
            //根据scoreId 查询对应templateId  查询所有的模块和级联查询模块项
            Template template = templateMapper.queryById(testScore.getTemplateId());
            map.put("template", template);

            // 创建一个集合存放 每一个模板项id 的平均分 [{templateItemId:10,avg:61}]
            List<Map> scoreAvgs=new ArrayList<>();
            //遍历每一个模板的模板项  对应模板项Id
            for(TemplateItem item:((Template)map.get("template")).getTemplateItems()){
                float avg = scoreItemMapper.queryAvg(item.getItemid());
                Map scoreAvg=new HashMap();
                scoreAvg.put("templateItemId",item.getItemid());
                scoreAvg.put("avg",avg);
                scoreAvgs.add(scoreAvg);
            }
            map.put("scoreAvgs",scoreAvgs);

            result.setData(map);
        }
        return result;
    }


    @Override
    public K12Result queryAndStudent(Map map) {
        K12Result result = K12Result.ok();
        //System.out.println("testScoreMap:"+map);

        PageInfo<TestScore> pageInfo = new PageInfo();

        int page = new Integer(map.get("page").toString());
        int rows = new Integer(map.get("row").toString());
        pageInfo.setPage(page);
        pageInfo.setRow(rows);
        //总条数
        int total = testScoreMapper.total(map);
        pageInfo.setTotal(total);
        int maxPageNum = (int) (Math.ceil(total * 1.0 / rows));
        pageInfo.setMaxPageNun(maxPageNum);
        //计算分页栏位置
        int pageStart = 1;
        int pageEnd = 10;
        if (page - 4 > 1) {
            pageStart = page - 4;
        }
        if (page + 5 > maxPageNum) {
            pageEnd = maxPageNum;
        }
        pageInfo.setPageStart(pageStart);
        pageInfo.setPageEnd(pageEnd);
        //数据 放在 pageInfo.data

        pageInfo.setData(testScoreMapper.queryAndStudent(map));

        result.setData(pageInfo);
        return result;
    }

    /**
     *  vo里有一个 testScore 对象 和 scoreItem集合
     * @param vo
     * @return
     */
    @Override
    public K12Result save(TestScoreSaveVo vo) {
        K12Result result = K12Result.error();
        TestScore testScore = vo.getTestScore();
        //补全数据
        Date date = new Date();
        testScore.setCreateTime(date);
        testScore.setModifyTime(date);
        testScore.setScoreStatus(1);
        if (testScoreMapper.insert(testScore) == 1) {
            Long scoreId = testScore.getScoreId();
            List<ScoreItem> scoreItems = new ArrayList<>();
            //类型转换
            List<Map> scoreItemMap = vo.getScoreItems();

            for (Map map : scoreItemMap) {
                ScoreItem scoreItem = new ScoreItem();
                scoreItem.setScoreId(scoreId);
                scoreItem.setScore((long) (Double.parseDouble(map.get("score").toString())));
                scoreItem.setTemplateItemId(Long.parseLong(map.get("itemid").toString()));
                scoreItems.add(scoreItem);
            }
            // 插入多个
            // System.out.println("scoreItems:"+scoreItems);
            scoreItemMapper.insertBatch(scoreItems);
            result = K12Result.ok();
        }

        return result;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param scoreId 主键
     * @return 实例对象
     */
    @Override
    public TestScore queryById(Long scoreId) {
        return this.testScoreMapper.queryById(scoreId);
    }


    /**
     * 新增数据
     *
     * @param testScore 实例对象
     * @return 实例对象
     */
    @Override
    public TestScore insert(TestScore testScore) {
        this.testScoreMapper.insert(testScore);
        return testScore;
    }

    /**
     * 修改数据
     *
     * @param testScore 实例对象
     * @return 实例对象
     */
    @Override
    public TestScore update(TestScore testScore) {
        this.testScoreMapper.update(testScore);
        return this.queryById(testScore.getScoreId());
    }

    /**
     * 通过主键删除数据
     *
     * @param scoreId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long scoreId) {
        return this.testScoreMapper.deleteById(scoreId) > 0;
    }
}
